#!/usr/bin/perl

# This is barely documented, and unlicensed.  It's badly coded too! You've been
# warned...

use Time::Format qw(%time);
use Image::Magick;
use Image::ImageShack;
use DB_File;

use strict;
no strict "refs";

# Variables! yay... or ick!.
my ( $version, $fqdn, $kernel, $wms, $gtktheme, $gtkicon, $gtkfont, $wmtheme, $xdfont, $wall, $scheme, $monitor );
my ( $headertext, $valuetext, $displayname, $displayfont, $displayfontsize, $displayfontheadercolor, $displayfontvaluecolor );
my ( $date, $count, $fullfile, $thumbfile );
my $image = Image::Magick->new;

my @targets = &checkargs( @ARGV );

$date  = $time{ 'yyyymmdd' };    # Define a filename based on todays date.
$count = 6;                      # Seconds to wait until snapshot is taken.

$fullfile  = "$ENV{HOME}/$date.png";          # Where to stash our full size capture
$thumbfile = "$ENV{HOME}/$date-thumb.png";    # Where to stash our thumbnail

$displayname     = "Charles Mauch (xterminus)";            # For annotation
$displayfont     = "/usr/share/fonts/TTF/aquafont.ttf";    # For annotation
$displayfontsize = "13";                                   # For annotation

# Remember to double escape wildcards, eg instead of \s, try \\s
$version  = grepfile( "/etc/arch-release",                                    "(.*)" );
$fqdn     = grepfile( "hostname -f |",                                        "(.*)" );
$kernel   = grepfile( "uname -r |",                                           "(.*)" );
$wms      = grepfile( "openbox --version |",                                  "(.*)" );
$scheme   = grepfile( "wallpaper schemedata$monitor |",                       "(.*)" );
$wall     = grepfile( "wallpaper current$monitor |",                          "(.*)" );
$gtktheme = grepfile( "gconftool-2 -g /desktop/gnome/interface/gtk_theme |",  "(.*)" );
$gtkicon  = grepfile( "gconftool-2 -g /desktop/gnome/interface/icon_theme |", "(.*)" );
$gtkfont  = grepfile( "gconftool-2 -g /desktop/gnome/interface/font_name |",  "(.*)" );
$wmtheme  = grepfile( "$ENV{HOME}/.config/openbox/rc.xml",                    "<theme>\\n.*<name>(.+)<\/name>" );
$xdfont   = grepfile( "$ENV{HOME}/.Xdefaults",                                "urxvt\\*font\\:\\s+(.+)" );

# Cleanup wallpaper name
$wall =~ s/\/home\/cpm\/dotfiles\/X\/backgrounds\///g;    # Remove boring path info
$wall =~ s/Center\_|Right\_|Left\_|Tile\_//g;             # Remove my naming conventions
$wall =~ s/_#\.\.\.\.\.\._//g;                            # Remove my naming conventions

# Now that we have our variables, lets define the text to output.
$headertext = "
screenshot $fullfile, on $fqdn 

OS             :
Kernel         :
Window Manager :
WM Theme       :
GTK Theme      :
GTK Font Theme :
GTK Icon Theme :
Urxvt Font     :
Wallpaper      :";

$valuetext = "


$version
$kernel
$wms
$wmtheme
$gtktheme
$gtkfont
$gtkicon
$xdfont
$wall";

# And the main progam is 2 lines.

&capture;

if ( @targets ) {
    for my $target ( @targets ) {
        &taclug  if ( $target eq "taclug" );
        &gallery if ( $target eq "gallery" );
        &shack   if ( $target eq "shack" );
    }
}

system( "gqview /home/cpm" );

exit( 0 );

# Handles image capture, with imagemagick just ... uhm, because.
sub capture {
    my ( $captured, $overlay, $backtile, $brand, $shadow );

    my @colors      = split( ':', $scheme );
    my $backcolor   = $colors[1];
    my $bordercolor = $colors[2];
    my $brighttext  = $colors[4];
    my $dimtext     = $colors[3];

    $image->Read( "| import -window root -silent -quiet -display $monitor -" );
    $image->Read( '/home/cpm/dotfiles/X/backgrounds/blank.png' );
    $image->Read( '/home/cpm/dotfiles/X/backgrounds/backtile.jpg' );
    $image->Read( '/home/cpm/dotfiles/X/backgrounds/brand.png' );

    $captured = $image->[0];    # Create references to array items.
    $overlay  = $image->[1];
    $backtile = $image->[2];
    $brand    = $image->[3];

    $overlay->Resize( geometry => '!410x170' );
    $overlay->Texture( Texture => $backtile );
    $overlay->Colorize( fill => '#' . $backcolor, opacity => '92' );
    $overlay->Border( geometry => "2x2", fill => "#" . $bordercolor );

    $overlay->Composite( image   => $brand,
                         compose => 'atop',
                         opacity => '50',
                         gravity => 'NorthEast',
                         x       => '20',
                         y       => '50'
                       );

    $overlay->Annotate( font        => $displayfont,
                        pointsize   => $displayfontsize,
                        fill        => "#" . $dimtext,
                        stroke      => "#" . $bordercolor,
                        strokewidth => 1,
                        gravity     => 'SouthWest',
                        x           => '10',
                        y           => '10',
                        text        => $headertext
                      );
    $overlay->Annotate( font      => $displayfont,
                        pointsize => $displayfontsize,
                        fill      => "#" . $dimtext,
                        stroke    => 'none',
                        gravity   => 'SouthWest',
                        x         => '10',
                        y         => '10',
                        text      => $headertext
                      );

    $overlay->Annotate( font        => $displayfont,
                        pointsize   => $displayfontsize,
                        fill        => "#" . $brighttext,
                        stroke      => "#" . $bordercolor,
                        strokewidth => 1,
                        gravity     => 'SouthWest',
                        x           => '125',
                        y           => '10',
                        text        => $valuetext
                      );
    $overlay->Annotate( font      => $displayfont,
                        pointsize => $displayfontsize,
                        fill      => "#" . $brighttext,
                        stroke    => 'none',
                        gravity   => 'SouthWest',
                        x         => '125',
                        y         => '10',
                        text      => $valuetext
                      );

    $shadow = $overlay->Clone();
    $shadow->Set( background => 'black' );
    $shadow->Shadow( opacity => '50', sigma => '2' );

    $captured->Composite( image   => $shadow,
                          compose => 'atop',
                          opacity => '50',
                          gravity => 'SouthWest',
                          x       => '20',
                          y       => '18'
                        );

    $captured->Composite( image   => $overlay,
                          compose => 'atop',
                          opacity => '50',
                          gravity => 'SouthWest',
                          x       => '20',
                          y       => '25'
                        );

    $captured->Write( filename => $fullfile, compression => 'None' );

    $captured->Scale( geometry => "200x200" );
    $captured->Border( geometry => "2x2", fill => "white" );
    $captured->Border( geometry => "1x1", fill => "black" );
    $captured->Write( filename => $thumbfile, compression => 'None' );
} ## end sub capture

sub taclug {

    print "Uploading to Taclug.org\n";
    system( "convert /home/cpm/$date.png /home/cpm/$date.jpg" );
    system( "convert /home/cpm/$date-thumb.png /home/cpm/$date-thumb.jpg" );
    system( "scp ~/$date.jpg cmauch\@taclug.org:~/public_html/screenshots/" );
    system( "scp ~/$date-thumb.jpg cmauch\@taclug.org:~/public_html/screenshots/" );
    system( "ssh cmauch\@taclug.org \"cd ~/public_html ; ln -sf ./screenshots/$date.jpg ./screenshot.jpg\"" );
    system( "rm /home/cpm/$date*.jpg" );

} ## end sub taclug

sub gallery {
    print "Adding to gallery\n";
    system( "rm /opt/debian/var/www/cmauch/shutter/geeky/desktop.screenshots/$date.jpg" );
    system( "rm /opt/debian/var/www/cmauch/shutter/geeky/desktop.screenshots/scale/$date-*.jpg" );
    system( "convert /home/cpm/$date.png /opt/debian/var/www/cmauch/shutter/geeky/desktop.screenshots/$date.jpg" );
    system( "cd /opt/debian/var/www/cmauch/shutter/geeky/desktop.screenshots/; ../../taimg index title location" );
    system( "cd /opt/debian/var/www/cmauch/shutter/geeky/desktop.screenshots/; ../../taimg conv" );
    system( "cd /opt/debian/var/www/cmauch/shutter/geeky/desktop.screenshots/; sort -r index.cat > index.cat2 ; mv index.cat2 index.cat" );
} ## end sub gallery

sub shack {
    print "Adding to imageshack\n";
    my $ishack = Image::ImageShack->new();
    $ishack->login( "REPLACE_WITH_IMAGESHACK_ID" );
    $ishack->host( "/home/cpm/$date.png" );
    print "\nWiki Link:\n";
    print "[" . $ishack->{ 'hosted' } . " " . $ishack->{ 'hosted_thumb' } . "]\n";
    print "Forum Link:\n";
    print "[URL=" . $ishack->{ 'hosted' } . "][IMG]" . $ishack->{ 'hosted_thumb' } . "][/IMG][/URL]\n";
} ## end sub shack

# Universal config variable grepper
sub grepfile {

    # Two arguments, file to parse and a match regexp to hunt for
    my ( $file, $string ) = @_;
    die "Throw me a friggen bone here!" if ( ( !$file ) or ( !$string ) );
    my ( $readfile );

    # Read file, storing entire file into $readfile variable.
    open( FH, $file );
    while ( <FH> ) {
        $readfile .= $_;
    }
    close( FH );

    my ( $result ) = $readfile =~ m/$string/gi;    # Grab first line w/ a match (case insensitive)

  return $result;
} ## end sub grepfile

sub checkargs {
    my @args    = @_;
    my $numargs = scalar @_;

    &displayhelp if ( $args[0] =~ /\?|\-?\-help|\-h/ );

    my $command = shift( @args );

    if ( $command eq "--display" ) {
        $monitor = shift( @args );
        if ( $monitor ) {
            print "Monitor: $monitor\n";
            $command = shift( @args );
        } else {
            &displayhelp;
        }
    } else {
        $monitor = $ENV{ 'DISPLAY' } or &displayhelp;
    }

    if ( $command eq "--target" ) {
        if ( @args ) {
            for my $target ( @args ) {
              return @args;
            }
        } else {
            &displayhelp;
        }
    } else {
        print "No target, saving files in $ENV{ 'HOME' }\n";
      return undef;
    }

    sub displayhelp {
        die( "Possible arguments are --display followed by the display name and --target followed by a subroutine target...\n" );
    }
} ## end sub checkargs
